<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Schema\LoginSchema;
use App\Schema\UserSchema;
use App\Service\Dao\UserDao;
use Han\Utils\Service;
use Hyperf\Di\Annotation\Inject;

class LoginService extends Service
{
    #[Inject]
    protected UserDao $userDao;

    public function register(string $username, string $password): UserSchema
    {
        if (empty($username) || empty($password)) {
            throw new BusinessException(ErrorCode::LOGIN_FAILED);
        }
        $model = $this->userDao->firstOrCreate($username, $password);
        if (!$model) {
            throw new BusinessException(ErrorCode::REGISTER_FAILED_HAS_USER);
        }

        return new UserSchema($model);
    }

    public function login(string $username, string $password): LoginSchema
    {
        if (empty($username) || empty($password)) {
            throw new BusinessException(ErrorCode::LOGIN_FAILED);
        }
        $model = $this->userDao->firstByName($username);
        if (!$model) {
            throw new BusinessException(ErrorCode::LOGIN_FAILED_AUTH);
        }
        if ($model->password !== md5($password)) {
            throw new BusinessException(ErrorCode::LOGIN_FAILED_AUTH);
        }
        $userAuth = UserAuth::instance()->init($model);

        return new LoginSchema($userAuth->getToken());
    }
}
